import { appointmentReback, completeAppointment } from '@/api/appointment';
import { completeOrder, orderList, orderListInPending, orderListInProgress, orderReback } from '@/api/order';
import { useUserStore, useCommonStore } from '@/store';
import { Image, View, Text, BaseEventOrig } from '@tarojs/components'
import Taro from '@tarojs/taro';
import { useEffect, useState } from 'react';
import { AtButton, AtMessage, AtTabs, AtTabsPane, AtTag, AtToast } from 'taro-ui'

export default function Order() {

  const [state, setState] = useState<number>();
  const handleClick = (value: number) => setState(value);

  const userStore = useUserStore();
  const commonStore = useCommonStore();

  const [allOrderList, setAllOrderList] = useState<OrderList[]>([]);
  const [isOk, setIsOk] = useState<boolean>(false);

  const [orderProgressList, setOrderProgressList] = useState<OrderList[]>([]);
  const [orderPendingList, setOrderPendingList] = useState<OrderList[]>([]);

  // 获取所有的订单
  const fetchOrderList = async () => {
    const { data } = await orderList();
    setAllOrderList(data);
  }

  // 获取待服务的订单
  const fetchOrderPending = async () => {
    const { data } = await orderListInPending();
    setOrderPendingList(data);
  }

  // 获取服务中的订单
  const fetchOrderProgress = async () => {
    const { data } = await orderListInProgress();
    setOrderProgressList(data);
  }

  const fetchData = () => {
    fetchOrderList();
    fetchOrderPending();
    fetchOrderProgress();
  }

  useEffect(() => {
    if (userStore.token === "") {
      Taro.redirectTo({ url: "/pages/user/index" });
      return;
    }

    fetchData()
  }, [userStore.token])

  useEffect(() => {
    commonStore.setSelectedIndex(0);
  }, [])

  const handleCompleteOrder = async (orderId: number, orderType: boolean, e: BaseEventOrig) => {
    e.stopPropagation();
    if (orderType) {
      const data = await completeOrder(orderId);
      if (data.code === 200) {
        setIsOk(true);
        fetchOrderList();
        setIsOk(false);
      }
    } else {
      const data = await completeAppointment(orderId);
      if (data.code === 200) {
        setIsOk(true);
        fetchOrderList();
        setIsOk(false);
      }
    }
  }

  Taro.usePullDownRefresh(() => {
    fetchData();
  });

  const handleComment = (employeeId: number, orderId: number, orderType: boolean, status: string, e?: BaseEventOrig) => {
    if (e) {
      e.stopPropagation();
    }
    Taro.navigateTo({ url: `/pages/employee-info/index?employeeId=${employeeId}&orderId=${orderId}&orderType=${orderType}&status=${status}` })
  }

  const renderOrderItem = (item: OrderList) => (
    <View key={item.id} className='flex flex-col px-3 py-2 rounded-md bg-white' onClick={() => handleComment(item.worker, item.id, item.orderType, item.status)}>
      <View className='flex gap-x-5 items-center'>
        <Image src={item.servicePic} className='h-24 w-24 rounded-md flex-shrink-0' />
        <View className='flex flex-col w-full'>
          <View className='flex gap-x-3 items-center'>
            <Text className='text-[#6190E8] text-xs font-semibold'>服务员工</Text>
            <Text className='text-sm'>{item.workerName}</Text>
          </View>
          <View className='flex gap-x-3 items-center'>
            <Text className='text-[#6190E8] text-xs font-semibold'>付款</Text>
            <Text className='text-sm'>{item.price} 元</Text>
          </View>

          <View className='w-full'>
            <AtTag size='small' className='flex-shrink-0' customStyle={
              item.status === 'pending' ?
                { color: "white", background: "#FF7F50", fontWeight: "bold" } :
                item.status === "progress" ?
                  { color: "white", background: "#FF6347", fontWeight: "bold" } :
                  { color: "white", background: "#32CD32", fontWeight: "bold" }}
            >
              {
                item.status === 'pending' ? '待服务' :
                  item.status === 'progress' ? '进行中' :
                    item.status === 'completed' ? '已完成' :
                      ''
              }
            </AtTag>

            <View className='mt-2 text-xs flex gap-x-3'>
              <Text className='text-[#6190E8] font-semibold'>下单时间</Text>
              <Text>{item.startTime}</Text>
            </View>

            <View className='flex justify-around items-center mt-4'>
              {
                item.status !== 'completed'
                  ?
                  <>
                    <AtButton size='small' disabled={item.reback} onClick={async (e) => {
                      e.stopPropagation();
                      let data: BaseResponse<string>;
                      if (item.orderType) {
                        data = await orderReback(item.id);
                      } else {
                        data = await appointmentReback(item.id);
                      }
                      if (data.code === 200) {
                        fetchData();
                        Taro.atMessage({
                          type: "success",
                          message: "提交成功",
                          duration: 1000
                        })
                      }
                    }}
                    >
                      {
                        item.reback
                          ?
                          '正在审核退款'
                          :
                          '申请退款'
                      }
                    </AtButton>
                    {
                      (!item.reback) && <AtButton size='small' type='primary' onClick={(e) => handleCompleteOrder(item.id, item.orderType, e)}>确认收货</AtButton>
                    }
                  </>
                  :
                  <>
                    <AtButton onClick={(e: BaseEventOrig) => handleComment(item.worker, item.id, item.orderType, item.status, e)} size='small' className={item.commented ? 'w-full bg-[#6190E8] text-white font-semibold' : 'w-full font-semibold'} disabled={item.commented}>{item.commented ? "已评价" : "去评价"}</AtButton>
                  </>
              }
            </View>
          </View>

        </View>
      </View>

      <View className='flex gap-x-3 overflow-x-auto items-center mt-2'>
        <Text className='text-[#6190E8] text-xs font-semibold flex-shrink-0'>下单地址</Text>
        <Text className='text-sm address'>{item.address}</Text>
      </View>
    </View >
  );

  return (
    <View className='order'>
      <AtTabs
        current={state!}
        scroll
        tabList={[
          { title: '全部' },
          { title: '待服务' },
          { title: '服务中' },
        ]}
        onClick={handleClick}
      >
        <AtTabsPane current={state!} index={0}>
          <View className='overflow-auto p-5 bg-gray-100 flex flex-col gap-y-2' style={{ height: "calc(100vh - 120px)" }}>
            {
              allOrderList.length === 0
                ?
                <View className='text-2xl font-bold text-[#6190E8] text-center'>暂无订单</View>
                :
                allOrderList.map(item => renderOrderItem(item))
            }
          </View>

        </AtTabsPane>
        <AtTabsPane current={state!} index={1}>
          <View className='overflow-auto p-5 bg-gray-100 flex flex-col gap-y-2' style={{ height: "calc(100vh - 120px)" }}>
            {
              orderPendingList.length === 0
                ?
                <View className='text-2xl font-bold text-[#6190E8] text-center'>暂无订单</View>
                :
                orderPendingList?.map(item => renderOrderItem(item))
            }
          </View>
        </AtTabsPane>
        <AtTabsPane current={state!} index={2}>
          <View className='overflow-auto p-5 bg-gray-100 flex flex-col gap-y-2' style={{ height: "calc(100vh - 120px)" }}>
            {
              orderProgressList.length === 0
                ?
                <View className='text-2xl font-bold text-[#6190E8] text-center'>暂无订单</View>
                :
                orderProgressList.map(item => renderOrderItem(item))
            }
          </View>
        </AtTabsPane>
      </AtTabs>

      <AtMessage />
      <AtToast isOpened={isOk} text='成功' status='success' duration={1000} />
    </View>
  )
}
